import React, { createContext, useContext, useEffect, useState } from 'react';
import { useColorScheme } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

interface ThemeColors {
  primary: string;
  secondary: string;
  background: string;
  card: string;
  text: string;
  border: string;
  placeholder: string;
  error: string;
}

interface Theme {
  colors: ThemeColors;
  isDark: boolean;
}

const lightTheme: Theme = {
  isDark: false,
  colors: {
    primary: '#007AFF',
    secondary: '#5856D6',
    background: '#F8F9FA',
    card: '#FFFFFF',
    text: '#1A1A1A',
    border: '#E5E5EA',
    placeholder: '#A0A0A5',
    error: '#FF3B30',
  },
};

const darkTheme: Theme = {
  isDark: true,
  colors: {
    primary: '#0A84FF',
    secondary: '#5E5CE6',
    background: '#121212',
    card: '#1E1E1E',
    text: '#F8F9FA',
    border: '#2C2C2E',
    placeholder: '#8E8E93',
    error: '#FF453A',
  },
};

interface ThemeContextValue {
  theme: Theme;
  toggleTheme: () => void;
  setThemeMode: (mode: 'light' | 'dark' | 'system') => void;
  themeMode: 'light' | 'dark' | 'system';
}

const ThemeContext = createContext<ThemeContextValue>({
  theme: lightTheme,
  toggleTheme: () => {},
  setThemeMode: () => {},
  themeMode: 'system',
});

const THEME_STORAGE_KEY = '@theme_mode';

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const systemColorScheme = useColorScheme();
  const [theme, setTheme] = useState<Theme>(systemColorScheme === 'dark' ? darkTheme : lightTheme);
  const [themeMode, setThemeMode] = useState<'light' | 'dark' | 'system'>('system');
  const [isLoading, setIsLoading] = useState(true);

  // 加载保存的主题设置
  useEffect(() => {
    async function loadThemePreference() {
      try {
        const savedThemeMode = await AsyncStorage.getItem(THEME_STORAGE_KEY);
        if (savedThemeMode) {
          setThemeMode(savedThemeMode as 'light' | 'dark' | 'system');
        }
      } catch (error) {
        console.error('加载主题偏好设置失败:', error);
      } finally {
        setIsLoading(false);
      }
    }
    loadThemePreference();
  }, []);

  // 保存主题设置
  const saveThemePreference = async (mode: 'light' | 'dark' | 'system') => {
    try {
      await AsyncStorage.setItem(THEME_STORAGE_KEY, mode);
    } catch (error) {
      console.error('保存主题偏好设置失败:', error);
    }
  };

  // 根据主题模式和系统设置更新主题
  useEffect(() => {
    console.log('当前主题模式:', themeMode);
    console.log('系统颜色方案:', systemColorScheme);
    
    let newTheme: Theme;
    switch (themeMode) {
      case 'light':
        newTheme = lightTheme;
        break;
      case 'dark':
        newTheme = darkTheme;
        break;
      case 'system':
        newTheme = systemColorScheme === 'dark' ? darkTheme : lightTheme;
        break;
      default:
        newTheme = lightTheme;
    }
    
    console.log('设置新主题:', newTheme.isDark ? 'dark' : 'light');
    setTheme(newTheme);
  }, [themeMode, systemColorScheme]);

  const toggleTheme = () => {
    const newMode = themeMode === 'system' 
      ? (systemColorScheme === 'dark' ? 'light' : 'dark')
      : (themeMode === 'dark' ? 'light' : 'dark');
    setThemeMode(newMode);
    saveThemePreference(newMode);
  };

  const handleSetThemeMode = (mode: 'light' | 'dark' | 'system') => {
    setThemeMode(mode);
    saveThemePreference(mode);
  };

  const value = {
    theme,
    toggleTheme,
    setThemeMode: handleSetThemeMode,
    themeMode,
  };

  if (isLoading) {
    return null;
  }

  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
} 